
package com.dtguai.admin.web.sys.service.impl;


import com.dtguai.admin.common.cache.CacheKeys;
import com.dtguai.admin.common.exception.DefinedException;
import com.dtguai.admin.util.redis.RedisUtil;
import com.dtguai.admin.web.sys.service.SysCaptchaService;
import com.google.code.kaptcha.Producer;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.awt.image.BufferedImage;
import java.util.Date;

/**
 * 验证码
 *
 * @author guo
 * @date 2019年6月26日17:09:10
 */
@Service("sysAuthCodeService")
@Slf4j
public class SysCaptchaServiceImpl implements SysCaptchaService {

    @Autowired
    private Producer producer;

    @Autowired
    RedisUtil redisUtil;


    @Override
    public BufferedImage getCaptcha(String uuid) {
        if (StringUtils.isBlank(uuid)) {
            log.error("验证码uuid为空{}", new Date());
            throw new DefinedException("uuid不能为空");
        }
        //生成文字验证码
        String code = producer.createText();

        //5分钟后过期
        redisUtil.setString(CacheKeys.AUTH_CODE_KEY + uuid, code, 300);
        return producer.createImage(code);
    }

    @Override
    public boolean validate(String uuid, String code) {
        String cacheCode = redisUtil.getString(CacheKeys.AUTH_CODE_KEY + uuid);
        if (cacheCode != null && cacheCode.equalsIgnoreCase(code)) {
            //删除验证码
            redisUtil.delete(CacheKeys.AUTH_CODE_KEY + uuid);
            return true;
        }
        return false;

    }
}
